/*
 * @Author: your name
 * @Date: 2021-03-30 13:36:03
 * @LastEditTime: 2021-04-02 13:00:56
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \my-app-koa\routes\api\profile.js
 */
const Router = require("koa-router")
const router = new Router()
const passport = require('koa-passport')
// 引入Profile
const Profile = require("../../models/Profile")
// 引入User
const User = require("../../models/User")

// 引入input验证
const validateProfileInput = require("../../validation/profile")
const validateExperienceInput = require("../../validation/experience")
const validateEducationInput = require("../../validation/education")


/**
 * @route GET api/profile/test
 * @desc 测试接口地址
 * @access 接口公开的
 */

router.get('/test', async ctx => {
  ctx.status = 200
  ctx.body = {
    msg: 'profile is ok'
  }
})


/**
 * @route GET api/profile/
 * @desc 获取用户信息+详细信息
 * @access 接口公开的
 */
router.get('/', passport.authenticate('jwt', { session: false }), async ctx => {
  const user = ctx.state.user
  console.log(user)
  const profile = await Profile.find({ user: ctx.state.user.id }).populate('user', ['name', 'email', 'avatar'])
  if (profile) {
    ctx.status = 200
    ctx.body = profile[0]
  } else {
    ctx.status = 400
    ctx.body = {
      noprofile: '未找到该用户信息'
    }
  }
})

/**
 * @route POST api/profile/
 * @desc 更新用户详细信息
 * @access 接口公开的
 */
router.post('/', passport.authenticate('jwt', { session: false }), async ctx => {

  const { errors, isValid } = validateProfileInput(ctx.request.body)
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }

  const user = ctx.state.user

  let Profiles = {}
  Profiles.user = user._id
  let {
    handle, company, avatar, website, location, status, skills, bio, githubusername,
    wechat, QQ, tengxunkt, wangyikt
  } = ctx.request.body
  if (skills) {
    skills = skills.split(",")
  }
  let social = {
    wechat, QQ, tengxunkt, wangyikt
  }
  Profiles = {
    ...Profiles,
    skills,
    social, handle, company, avatar, website, location, status, bio, githubusername,
  }
  // 查询数据库
  const profile = await Profile.find({ user: user.id });
  if (profile.length) {
    // 编辑更新
    const profileUpdate = await Profile.findOneAndUpdate({ user: user.id }, { $set: Profiles }, { new: true });
    ctx.body = profileUpdate
  } else {
    await new Profile(Profiles).save().then(newProfile => {
      ctx.status = 200
      ctx.body = newProfile
    })
  }

})


/**
 * @route GET api/profile/handle?handle=test
 * @desc 通过handle获取用户个人信息
 * @access 接口公开的
 */

router.get('/handle/:handle', async ctx => {
  let errors = {};
  const { handle } = ctx.params
  if (!handle) {
    ctx.staus = 400;
    ctx.body = {
      msg: '用户名不能为空'
    }
    return
  }
  const profile = await Profile.find({ handle: handle }).populate('user', ['name', 'email', 'avatar'])
  if (profile) {
    ctx.status = 200
    ctx.body = profile[0]
  } else {
    errors.noprofile = "信息不存在"
    ctx.status = 404
    ctx.body = errors
  }

})

/**
 * @route GET api/profile/user?user_id=xxx
 * @desc 通过user_id获取用户个人信息
 * @access 接口公开的
 */

router.get('/user', async ctx => {
  let errors = {};
  const { user_id } = ctx.query
  if (!user_id) {
    ctx.staus = 400;
    ctx.body = {
      msg: '用户id不能为空'
    }
    return
  }
  const profile = await Profile.find({ user: user_id }).populate('user', ['name', 'email', 'avatar'])
  if (profile) {
    ctx.status = 200
    ctx.body = profile[0]
  } else {
    errors.noprofile = "信息不存在"
    ctx.status = 404
    ctx.body = errors
  }

})


/**
 * @route GET api/profile/all
 * @desc 获取所有的用户信息
 * @access 接口公开的
 */

router.get('/all', async ctx => {
  let errors = {};
  const profiles = await Profile.find({}).populate('user', ['name', 'email', 'avatar'])
  if (profiles) {
    ctx.status = 200
    ctx.body = profiles
  } else {
    errors.noprofile = "没有任何用户信息"
    ctx.status = 404
    ctx.body = errors
  }

})


/**
 * @route POST api/profile/experience
 * @desc 更新用户详细信息-工作经历
 * @access 接口公开的
 */
router.post('/experience', passport.authenticate('jwt', { session: false }), async ctx => {

  const { errors, isValid } = validateExperienceInput(ctx.request.body)
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }
  const user = ctx.state.user
  experience = []
  let {
    title, company, location, from, to, description } = ctx.request.body
  experience.unshift({ title, company, location, from, to, description })
  // 查询数据库
  const profile = await Profile.find({ user: user.id });
  if (profile) {

    // 编辑更新
    const profileUpdate = await Profile.updateOne({ user: user.id }, { $push: { experience: experience } }, { $sort: 1 });
    if (profileUpdate.ok === 1) {
      ctx.status = 200
      const newProfiles = await Profile.find({ user: user.id }).populate('user', ['name', 'email', 'avatar'])
      ctx.body = newProfiles
    }

  } else {
    errors.msg = "用户不存"
    ctx.status = 404
    ctx.body = errors
  }
})



/**
 * @route DELETE api/profile/experience
 * @desc 删除用户详细信息-工作经历
 * @access 接口公开的
 */
router.delete('/experience/:exp_id', passport.authenticate('jwt', { session: false }), async ctx => {
  const { exp_id } = ctx.params
  if (!exp_id) {
    ctx.staus = 400;
    ctx.body = {
      msg: '请选择需要删除的工作经历'
    }
    return
  }

  const user = ctx.state.user

  // 查询数据库
  const profile = await Profile.find({ user: user.id });
  if (profile[0].experience.length > 0) {
    const removeIndex = profile[0].experience.map(v => v.id).indexOf(exp_id);
    profile[0].experience.splice(removeIndex, 1)

    // 编辑更新
    const profileUpdate = await Profile.findOneAndUpdate({ user: user.id }, { $set: profile[0] }, { new: true });
    ctx.status = 200
    ctx.body = profileUpdate
  } else {
    errors.msg = "经历不存在"
    ctx.status = 404
    ctx.body = errors
  }
})

/**
 * @route POST api/profile/education
 * @desc 更新用户详细信息-教育经历
 * @access 接口公开的
 */
router.post('/education', passport.authenticate('jwt', { session: false }), async ctx => {

  const { errors, isValid } = validateEducationInput(ctx.request.body)
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }
  const user = ctx.state.user
  const education = []
  let { school, degree, fieldofstudy, from, to, description } = ctx.request.body
  education.unshift({ school, degree, fieldofstudy, from, to, description })
  // 查询数据库
  const profile = await Profile.find({ user: user.id });
  if (profile) {
    // 编辑更新
    const profileUpdate = await Profile.updateOne({ user: user.id }, { $push: { education: education } }, { $sort: 1 });
    if (profileUpdate.ok === 1) {
      ctx.status = 200
      const newProfiles = await Profile.find({ user: user.id }).populate('user', ['name', 'email', 'avatar'])
      ctx.body = newProfiles
    }

  } else {
    errors.msg = "用户不存"
    ctx.status = 404
    ctx.body = errors
  }
})


/**
 * @route DELETE api/profile/experience
 * @desc 删除用户详细信息-工作经历
 * @access 接口公开的
 */
router.delete('/education/:edu_id', passport.authenticate('jwt', { session: false }), async ctx => {
  const { edu_id } = ctx.ctx.params
  if (!edu_id) {
    ctx.staus = 400;
    ctx.body = {
      msg: '请选择需要删除的工作经历'
    }
    return
  }

  const user = ctx.state.user

  // 查询数据库
  const profile = await Profile.find({ user: user.id });
  if (profile[0].education.length > 0) {
    const removeIndex = profile[0].education.map(v => v.id).indexOf(edu_id);
    profile[0].education.splice(removeIndex, 1)

    // 编辑更新
    const profileUpdate = await Profile.findOneAndUpdate({ user: user.id }, { $set: profile[0] }, { new: true });
    ctx.status = 200
    ctx.body = profileUpdate
  } else {
    errors.msg = "经历不存在"
    ctx.status = 404
    ctx.body = errors
  }
})

/**
 * @route DELETE api/profile/
 * @desc 删除整个用户
 * @access 接口公开的
 */
router.delete('/', passport.authenticate('jwt', { session: false }), async ctx => {
  // 查询数据库
  const profile = await Profile.deleteOne({ user: ctx.state.user.id });
  if (profile.ok === 1) {
    const user = await User.deleteOne({ _id: ctx.state.user.id })
    if (user.ok === 1) {
      ctx.status = 200
      ctx.body = {
        success: true
      }
    }
  } else {
    ctx.status = 404
    ctx.status = 200
    ctx.body = {
      error: "profile不存在"
    }
  }
})



module.exports = router.routes();